import React, { useEffect, useState } from 'react'
import styles from './login.module.css'
import { Input, Button } from 'antd-mobile'

//1.声明用户Id 和 服务 Id
const user_id = 1;
const server_id = 4562;

const ws = new WebSocket(
  `ws:124.221.74.149:8003/koa/ws?user_id=${user_id}&server_id=${server_id}`
);
function Index() {
  const [message, setmessage] = useState('')
  const [chatlist, setChatList] = useState([])
  useEffect(() => {
    ws.onopen = () => {
      console.log('连接成功')
      ws.send(JSON.stringify({ type: 'getChatList' }))
    }
    ws.onmessage = (msg) => {
      const { type, data } = JSON.parse(msg.data)
      console.log(type, data)
      if (type == 'getChatList') {
        setChatList(data)
      }
      else if (type == 'addMessage') {
        setChatList((pre) => [...pre, data])
      }
    }
  }, [])
  const fswz = () => {
    ws.send(JSON.stringify({
      type: 'addMessage',
      data: {
        user_id,
        server_id,
        message
      }
      
    }))
    setChatList('')
  }
  return (
    <div className={styles.lt}>
      <div>
        {
          chatlist.length>0&&chatlist.map((item, index) => {
            const zy = `chat-list-item-${item.dir == 1 ? 'right' : 'left'}`
            const tx = item.dir ? item.user_avatar : item.server_avatar
            return <div key={index} className={styles[zy]} >
              <div>
                <img className={styles.txx} src={tx} alt="" />
              </div>
              <div className={styles.wz}>{item.message}</div>
            </div>
          })
        }
      </div>
      <div className={styles.fs}>
        <Input
          placeholder='请输入内容'
          value={message}
          onChange={val => {
            setmessage(val)
          }}
        />
        <Button color='primary' fill='solid' onClick={() => fswz()}>
          发送
        </Button>
      </div>

    </div>
  )
}

export default Index
